﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using DMS.Business.Modules.Organization;
using DMS.Business.Utility;
using DMS.Business.WebControls;

namespace DMS.Web.Common.Controls
{
    public partial class DepartmentTreeScope : System.Web.UI.UserControl
    {
        #region 属性参数
        private object eventLocker = new object();
        private string _NavigateUrlTemplate = string.Empty;
        /// <summary>
        /// 节点跳转路径模板
        /// </summary>
        public string NavigateUrlTemplate
        {
            get
            {
                return this._NavigateUrlTemplate;
            }
            set
            {
                this._NavigateUrlTemplate = value;
            }
        }
        /// <summary>
        /// 节点点击目标
        /// </summary>
        public string Target
        {
            get
            {
                return this.tvDepts.Target;
            }
            set
            {
                this.tvDepts.Target = value;
            }
        }

        /// <summary>
        /// 是否显示节点复选框
        /// </summary>
        public TreeNodeTypes ShowCheckBoxes
        {
            get
            {
                return this.tvDepts.ShowCheckBoxes;
            }
            set
            {
                this.tvDepts.ShowCheckBoxes = value;
            }
        }
        public event TreeNodeEventHandler SelectedChanged
        {
            add
            {
                lock (eventLocker)
                {
                    this.tvDepts.TreeNodeCheckChanged += value;
                }
            }
            remove
            {
                lock (eventLocker)
                {
                    this.tvDepts.TreeNodeCheckChanged -= value;
                }
            }
        }
        public event EventHandler NodeClick
        {
            add
            {
                lock (eventLocker)
                {
                    this.tvDepts.SelectedNodeChanged += value;
                }
            }
            remove
            {
                lock (eventLocker)
                {
                    this.tvDepts.SelectedNodeChanged -= value;
                }
            }
        }
        public TreeNode SelectedItem
        {
            get
            {
                return this.tvDepts.SelectedNode;
            }
        }
        public TreeNodeCollection SelectedItems
        {
            get
            {
                return this.tvDepts.CheckedNodes;
            }
        }
        private string _StartDeptID = string.Empty;
        public string StartDeptID
        {
            get
            {
                return this._StartDeptID;
            }
            set
            {
                this._StartDeptID = value;
            }
        }
        private bool _AutoBind = true;
        public bool AutoBind
        {
            get
            {
                return this._AutoBind;
            }
            set
            {
                this._AutoBind = value;
            }
        }
        #endregion

        #region 控件事件
        /// <summary>
        /// 控件加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack && this.AutoBind)
            {
                this.InitTree();
            }
        }
        /// <summary>
        /// 展开部门树
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void tvDepts_TreeNodePopulate(object sender, TreeNodeEventArgs e)
        {
            TreeNode node = e.Node;
            node.ChildNodes.Clear();

            string deptID = node.Value;
            Department dept = UserHelper.GetDepartmentByID(deptID);
            if (dept != null)
            {
                List<Department> subDepts = UserHelper.GetSubDepartments(dept);

                foreach (Department subDept in subDepts)
                {
                    TreeNode subNode = this.CreateDeptNode(subDept);
                    node.ChildNodes.Add(subNode);
                }
            }
        }
        /// <summary>
        /// 选择节点复选框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void tvDepts_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
        {
        }
        #endregion

        #region 内部方法
        /// <summary>
        /// 初始化部门树
        /// </summary>
        public void InitTree()
        {
            this.tvDepts.Nodes.Clear();

            TreeNodePlus node = this.tvDepts.CreateNodePlus();
            node.SelectAction = TreeNodeSelectAction.Select;
            node.PopulateOnDemand = false;

            node.Text = "我的管理范围";
            node.Value = "";
            node.ToolTip = "我的管理范围";
            
            string url = this._NavigateUrlTemplate;
            if (this._NavigateUrlTemplate.Contains("{ID}"))
            {
                url = url.Replace("{ID}", "");
            }
           
            node.NavigateUrl = url;
            this.tvDepts.Nodes.Add(node);

            List<Department> rootDepts = new List<Department>();
            
            //this.StartDeptID = "5b2afe51-cfa2-4cb3-b85e-866ddd39e1c1";
            if (!string.IsNullOrEmpty(this.StartDeptID))
            {
                rootDepts.Add(UserHelper.GetDepartmentByID(StartDeptID));
            }
            else
            {
                string roleName = "";
                if (UserHelper.IsUserInRole(SystemContext.Current.LoginUser, "部门资产管理员"))
                {
                    roleName = "部门资产管理员";
                }
                else 
                {
                    roleName = "渠道资产申请员";
                }
                string scope = UserHelper.GetScopeIDs(roleName, SystemContext.Current.LoginUser.ID.ToString());
                string scopeIDs = "";
                if(string.IsNullOrEmpty(scope))
                {
                    scopeIDs="'D33E34DB-52FC-4102-92F5-B5569999A0CE'";
                }else
                {
                    foreach(string id in scope.Split(';'))
                    {
                        if(!string.IsNullOrEmpty(id))
                            scopeIDs += "'" + id + "',";
                    }
                    scopeIDs = scopeIDs.Substring(0, scopeIDs.Length - 1);
                }
                //rootDepts = UserHelper.GetScopeDepartments(scopeIDs);
                rootDepts = UserHelper.GetScopeDepartmentsSimple(scopeIDs);
            }
            if (rootDepts.Count > 0)
            {
                //for (int i = 0; i < rootDepts.Count; i++) 
                //{
                //    if (rootDepts[i] != null)
                //    {
                //        if (rootDepts[i].Level == 2)
                //        {
                //            TreeNode node = this.CreateDeptNode(rootDepts[i]);
                //            this.tvDepts.Nodes.Add(node);
                //            Guid pID = rootDepts[i].ID;
                //            rootDepts[i] = null;
                //            CreateScopeTree(node, rootDepts, pID);
                //        }
                //    }
                //}
                foreach(Department dept in rootDepts){
                    TreeNode nodeChild = this.CreateDeptNode(dept);
                    node.ChildNodes.Add(nodeChild);
                }

                this.dvEmptyMsg.Visible = false;
                this.tvDepts.Visible = true;
            }
            else
            {
                this.dvEmptyMsg.Visible = true;
                this.tvDepts.Visible = false;
            }
        }

        private void CreateScopeTree(TreeNode currentDeptNode, List<Department> depts, string pID)
        {
            for (int i = 0; i < depts.Count; i++) 
            {
                if (depts[i] != null && depts[i].ParentID == pID)
                {
                    string _pID = depts[i].ID;
                    TreeNode childNode = this.CreateDeptNode(depts[i]);
                    currentDeptNode.ChildNodes.Add(childNode);
                    depts[i]=null;
                    CreateScopeTree(childNode, depts, _pID);
                }
            }
        }

        /// <summary>
        /// 创建节点
        /// </summary>
        /// <param name="dept"></param>
        /// <returns></returns>
        private TreeNode CreateDeptNode(Department dept)
        {
            TreeNodePlus node = this.tvDepts.CreateNodePlus();
            node.SelectAction = TreeNodeSelectAction.Select;
            node.PopulateOnDemand = true;

            node.Text = dept.Name;
            node.Value = dept.ID.ToString();
            node.ToolTip = dept.FullName;
            node.NavigateUrl = this.CreateNodeNavigateUrl(dept);

            return node;
        }

        /// <summary>
        /// 构成节点导航路径 
        /// </summary>
        /// <param name="dept"></param>
        /// <returns></returns>
        private string CreateNodeNavigateUrl(Department dept)
        {
            string url = this._NavigateUrlTemplate;

            if (this._NavigateUrlTemplate.Contains("{ID}"))
            {
                url = url.Replace("{ID}", dept.ID.ToString());
            }
            if (this._NavigateUrlTemplate.Contains("{Name}"))
            {
                url = url.Replace("{Name}", dept.Name);
            }
            if (this._NavigateUrlTemplate.Contains("{FullName}"))
            {
                url = url.Replace("{FullName}", dept.FullName);
            }
            if (this._NavigateUrlTemplate.Contains("{Level}"))
            {
                url = url.Replace("{Level}", dept.Level.ToString());
            }

            return url;
        }
        #endregion


    }
}